﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MongoDB.Driver;
using SJ.Platform.Common;
using SJ.Platform.EFCore.Common;
using SJ.Platform.EFCore.DBOperation.DBOperation.MySQL.Project;
using SJ.Platform.EFCore.Model;
using SJ.Platform.EFCore.Model.FlowManager;
using SJ.Platform.EFCore.Model.ProjectManager;
using SJ.Platform.Extend.IOC.CurrentUser;
using SJ.Platform.Extend.ModelExtend.ProjectExt;
using SJ.Platform.Extend.Request;
using SJ.Platform.Extend.Response;
using SJ.Platform.File.DBOperation;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace SJ.Platform.Api.Controllers.ProjectManager
{
    /// <summary>
    /// 项目操作类
    /// </summary>
    [Route(GlobalVariableHandle.Scope_Api + "/Project")]
    [ApiController]
    [Authorize(GlobalVariableHandle.Scope_Api)]
    public class ProjectManagerController : ControllerBase
    {
        private readonly SJDBContext _context;
        private readonly ICurrentUser _currentUser;
        private readonly Project_MainHandle project_mainHandle;
        private readonly Project_StakeholderHandle project_StakeholderHandle;
        private readonly Project_DocumentHandle project_documentHandle;
        private readonly Project_SettingHandle project_SettingHandle;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext">数据库</param>
        /// <param name="currentUser">当前用户</param>
        public ProjectManagerController(SJDBContext dbContext, ICurrentUser currentUser)
        {
            _context = dbContext;
            _currentUser = currentUser;
            project_mainHandle = new Project_MainHandle(dbContext);
            project_StakeholderHandle = new Project_StakeholderHandle(dbContext);
            project_documentHandle = new Project_DocumentHandle(dbContext);
            project_SettingHandle = new Project_SettingHandle(dbContext);
        }

        /// <summary>
        /// 新增项目
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("CreateProjectAsync")]
        public async Task<IActionResult> CreateProjectAsync([FromBody] ProjectMainExtend model)
        {
            try
            {
                bool result = await TransactionHandle.ExecuteInTransactionAsync<bool>(_context, async () =>
                {
                    var Project = new ProjectMain
                    {
                        Id = Guid.NewGuid().ToString(),
                        ProjectName = model.ProjectName,
                        Basis = model.Basis,
                        Description = model.Description,
                        StartTime = model.StartTime,
                        EndTime = model.EndTime,
                        ManagerId = model.ManagerId,
                        ManagerName = model.ManagerName,
                        Status = model.Status,
                        AddTime = DateTime.Now,
                        AddUserId = _currentUser.UserId,
                        EditTime = DateTime.Now,
                        EditUserId = _currentUser.UserId
                    };
                    List<ProjectStakeholder> sList = new List<ProjectStakeholder>();
                    //发起人
                    if (!string.IsNullOrWhiteSpace(model.InitiatorName))
                    {
                        string[] initiatorNames = model.InitiatorName.Split(',');
                        string[] initiatorIds = model.InitiatorId.Split(",");
                        int i = 0;
                        foreach (string id in initiatorIds)
                        {
                            sList.Add(new ProjectStakeholder
                            {
                                ProjectId = Project.Id,
                                UserId = id,
                                RealName = initiatorNames[i],
                                StakeholderType = 1,
                                AddTime = DateTime.Now,
                                AddUserId = _currentUser.UserId
                            });
                            i++;
                        }
                    }

                    bool actionResult = await project_mainHandle.CreateAsync(Project);
                    if (sList.Count > 0 && actionResult)
                    {
                        actionResult = await project_StakeholderHandle.CreateAsync(sList);
                    }
                    //立项文档
                    if (model.projectDocuments != null && model.projectDocuments.Count > 0 && actionResult)
                    {
                        List<ProjectDocument> ds = new List<ProjectDocument>();
                        foreach (var document in model.projectDocuments)
                        {
                            ds.Add(new ProjectDocument
                            {
                                ProjectId = Project.Id,
                                FileName = document.FileName,
                                ObjectId = document.ObjectId,
                                DocType = document.DocType,
                                IsUsed = document.IsUsed,
                                AddTime = DateTime.Now,
                                AddUserId = _currentUser.UserId,
                                EditTime = DateTime.Now,
                                EditUserId = _currentUser.UserId,
                                Version = "1.0"
                            });
                        }
                        actionResult = await project_documentHandle.CreateAsync(ds);
                    }

                    return actionResult;
                });
                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "项目添加" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "项目添加失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 修改项目
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("UpdateProjectAsync")]
        public async Task<IActionResult> UpdateProjectAsync([FromBody] ProjectMainExtend model)
        {
            try
            {
                bool result = await TransactionHandle.ExecuteInTransactionAsync<bool>(_context, async () =>
                {
                    var Project = new ProjectMain
                    {
                        Id = model.Id,
                        ProjectName = model.ProjectName,
                        Basis = model.Basis,
                        Description = model.Description,
                        StartTime = model.StartTime,
                        EndTime = model.EndTime,
                        ManagerId = model.ManagerId,
                        ManagerName = model.ManagerName,
                        Status = model.Status,
                        AddTime = model.AddTime,
                        AddUserId = model.AddUserId,
                        EditTime = DateTime.Now,
                        EditUserId = _currentUser.UserId
                    };
                    List<ProjectStakeholder> sList = new List<ProjectStakeholder>();
                    //发起人
                    if (!string.IsNullOrWhiteSpace(model.InitiatorName))
                    {
                        string[] initiatorNames = model.InitiatorName.Split(',');
                        string[] initiatorIds = model.InitiatorId.Split(",");
                        int i = 0;
                        foreach (string id in initiatorIds)
                        {
                            sList.Add(new ProjectStakeholder
                            {
                                ProjectId = Project.Id,
                                UserId = id,
                                RealName = initiatorNames[i],
                                StakeholderType = 1,
                                AddTime = DateTime.Now,
                                AddUserId = _currentUser.UserId
                            });
                            i++;
                        }
                    }

                    bool actionResult = await project_mainHandle.UpdateAsync(Project);
                    if (sList.Count == 0 && actionResult)
                    {
                        actionResult = await project_StakeholderHandle.DeleteByProjectIdAsync(Project.Id, 1);
                    }
                    if (sList.Count > 0 && actionResult)
                    {
                        await project_StakeholderHandle.DeleteByProjectIdAsync(Project.Id, 1);
                        actionResult = await project_StakeholderHandle.CreateAsync(sList);
                    }

                    //立项文档
                    if (model.projectDocuments != null && model.projectDocuments.Count > 0 && actionResult)
                    {
                        List<ProjectDocument> ds = new List<ProjectDocument>();
                        foreach (var document in model.projectDocuments)
                        {
                            ds.Add(new ProjectDocument
                            {
                                ProjectId = Project.Id,
                                FileName = document.FileName,
                                ObjectId = document.ObjectId,
                                DocType = document.DocType,
                                IsUsed = document.IsUsed,
                                AddTime = DateTime.Now,
                                AddUserId = _currentUser.UserId,
                                EditTime = DateTime.Now,
                                EditUserId = _currentUser.UserId,
                                Version = "1.0"
                            });
                        }
                        actionResult = await project_documentHandle.CreateAsync(ds);
                    }

                    return actionResult;
                });

                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "项目修改" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "项目修改失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 更新项目指定的内容
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("UpdateProjectSpecificContentAsync")]
        public async Task<IActionResult> UpdateProjectSpecificContentAsync([FromBody] ProjectMainUpdateModelExtend model)
        {
            try
            {
                //默认更新最后修改时间和修改人
                model.EditTime = DateTime.Now;
                model.EditUserId = _currentUser.UserId;
                model.UpdateProperties.Add("EditTime");
                model.UpdateProperties.Add("EditUserId");
                bool result = await project_mainHandle.UpdateProjectSpecificContentAsync(model);
                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "项目更新" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "项目更新失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 删除项目
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        [HttpGet("DeleteByProjectIdAsync/{projectId}")]
        public async Task<IActionResult> DeleteByProjectIdAsync(string projectId)
        {
            try
            {
                bool result = await TransactionHandle.ExecuteInTransactionAsync<bool>(_context, async () =>
                {
                    bool actionResult = await project_mainHandle.DeleteByIdAsync(projectId);
                    if (actionResult)
                    {
                        actionResult = await project_StakeholderHandle.DeleteByProjectIdAsync(projectId);
                    }

                    return actionResult;
                });

                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "删除项目" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "删除项目失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 获取所有项目
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("GetAllProjectAsync")]
        public async Task<IActionResult> GetAllProjectAsync([FromBody] ApiPageQueryRequest<ProjectMain> request)
        {
            try
            {
                var result = await project_mainHandle.GetAllAsync((int)request.PageIndex, (int)request.PageSize, ApiPageQueryRequest<ProjectMain>.GenerateCondition(request.Condition));

                return Ok(ApiPageQueryResponse<List<ProjectMain>>.SetResponse(ApiResponseStatus.Success, "查询成功", (int)request.PageIndex, (int)request.PageSize, result.count, result.projects)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiPageQueryResponse<List<ProjectMain>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, (int)request.PageIndex, (int)request.PageSize, 0, new List<ProjectMain> { }));
            }
        }

        /// <summary>
        /// 获取创建人所有正在进行的项目
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        [HttpGet("GetAllProjectByCreateUserAsync/{status}")]
        public async Task<IActionResult> GetAllProjectByCreateUserAsync(int status)
        {
            try
            {
                var result = await project_mainHandle.GetAllProjectByCreateUserAsync(status, _currentUser.UserId);

                return Ok(ApiNormalResponse<List<ProjectMain>>.SetResponse(ApiResponseStatus.Success, "查询成功", result)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<List<ProjectMain>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, new List<ProjectMain> { }));
            }
        }

        /// <summary>
        /// 获取项目干系人
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="stakeholderType"></param>
        /// <returns></returns>
        [HttpGet("GetProjectStakeholderAsync/{projectId}/{stakeholderType}")]
        public async Task<IActionResult> GetProjectStakeholderAsync(string projectId, int stakeholderType)
        {
            try
            {
                List<ProjectStakeholder> result = new List<ProjectStakeholder>();
                if (stakeholderType == 0)
                {
                    result = await project_StakeholderHandle.GetEntityListByProjectIdAsync(projectId);
                }
                if (stakeholderType > 0)
                {
                    result = await project_StakeholderHandle.GetEntityListByProjectIdAsync(projectId, stakeholderType);
                }

                return Ok(ApiNormalResponse<List<ProjectStakeholder>>.SetResponse(ApiResponseStatus.Success, "查询成功", result)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<List<ProjectStakeholder>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, new List<ProjectStakeholder> { }));
            }
        }

        /// <summary>
        /// 获取项目详情
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        [HttpGet("GetProjectDetailAsync/{projectId}")]
        public async Task<IActionResult> GetProjectDetailAsync(string projectId)
        {
            try
            {
                var result = project_mainHandle.GetDetailByIdAsync(projectId).Result;

                return Ok(ApiNormalResponse<ProjectMainExtend>.SetResponse(ApiResponseStatus.Success, "查询成功", result)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<ProjectMainExtend>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, null));
            }
        }

        /// <summary>
        /// 获取项目文档
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="docType"></param>
        /// <returns></returns>
        [HttpGet("GetProjectDocmentsAsync/{projectId}/{docType}")]
        public async Task<IActionResult> GetProjectDocmentsAsync(string projectId, int docType)
        {
            try
            {
                List<ProjectDocument> result = new List<ProjectDocument>();
                if (docType == 0)
                {
                    result = await project_documentHandle.GetEntityListByProjectIdAsync(projectId);
                }
                if (docType > 0)
                {
                    result = await project_documentHandle.GetEntityListByProjectIdAsync(projectId, docType);
                }

                return Ok(ApiNormalResponse<List<ProjectDocument>>.SetResponse(ApiResponseStatus.Success, "查询成功", result)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<List<ProjectDocument>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, new List<ProjectDocument> { }));
            }
        }

        /// <summary>
        /// 删除项目文件
        /// </summary>
        /// <param name="objectId"></param>
        /// <returns></returns>
        [HttpGet("DeleteProjectDocByObjectIdAsync/{objectId}")]
        public async Task<IActionResult> DeleteProjectDocByObjectIdAsync(string objectId)
        {
            try
            {
                bool result = await project_mainHandle.DeleteProjectDocByObjectIdAsync(objectId);
                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "删除项目文件" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "删除项目文件失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 获取所有项目设置
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("GetAllProjectSettingAsync")]
        public async Task<IActionResult> GetAllProjectSettingAsync([FromBody] ApiPageQueryRequest<ProjectSetting> request)
        {
            try
            {
                var result = await project_SettingHandle.GetAllAsync((int)request.PageIndex, (int)request.PageSize, ApiPageQueryRequest<ProjectSetting>.GenerateCondition(request.Condition));

                return Ok(ApiPageQueryResponse<List<ProjectSetting>>.SetResponse(ApiResponseStatus.Success, "查询成功", (int)request.PageIndex, (int)request.PageSize, result.count, result.settings)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiPageQueryResponse<List<ProjectSetting>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, (int)request.PageIndex, (int)request.PageSize, 0, new List<ProjectSetting> { }));
            }
        }

        /// <summary>
        /// 新增项目设置
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("CreateProjectSettingAsync")]
        public async Task<IActionResult> CreateProjectSettingAsync([FromBody] ProjectSetting model)
        {
            var setting = new ProjectSetting
            {
                Id = Guid.NewGuid().ToString(),
                Skey = model.Skey,
                Svalue = model.Svalue,
                Stype = model.Stype
            };

            try
            {
                bool result = await project_SettingHandle.CreateAsync(setting);

                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "项目设置添加" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "项目设置添加失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 修改项目设置
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("UpdateProjectSettingAsync")]
        public async Task<IActionResult> UpdateProjectSettingAsync([FromBody] ProjectSetting model)
        {
            var setting = new ProjectSetting
            {
                Id = model.Id,
                Skey = model.Skey,
                Svalue = model.Svalue,
                Stype = model.Stype
            };

            try
            {
                bool result = await project_SettingHandle.UpdateAsync(setting);

                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "项目设置修改" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "项目设置修改失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 删除项目设置
        /// </summary>
        /// <param name="projectSettingId"></param>
        /// <returns></returns>
        [HttpGet("DeleteByProjectSettingIdAsync/{projectSettingId}")]
        public async Task<IActionResult> DeleteByProjectSettingIdAsync(string projectSettingId)
        {
            try
            {
                bool result = await project_SettingHandle.DeleteByIdAsync(projectSettingId);

                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "删除项目设置" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "删除项目设置失败：" + ex.Message, false));
            }
        }
    }
}
